<?php
namespace app\mp\home;
use app\common\controller\Common;

/**
 * 缩水机对接接口
 * @author King
 *
 */
class Device extends Common
{

	/**
	 * 缩水任务
	 *
	 * @author King
	 * @date 2021年5月7日
	 *
	 */
    public function shrink() {
    	$str = input('get.');
    	addLog(http_build_query($str), 'shrink');
    	echo json_encode(['status' => 1, 'message' => 'success']);
    }

    /**
     * 缩水详细幅宽数据
     *
     * @author King
     * @date 2021年5月7日
     *
     */
    public function shrinkWidth() {
    	$str = input('get.');
    	addLog(http_build_query($str), 'shrinkWidth');
    	echo json_encode(['status' => 1, 'message' => 'success']);
    }


    public function skuPicErrList(){
        $skucount = db('sku sku')->where("pic not like 'http://www.020mimo.com%' and pic_download_flag<>2 and ori_pic<>''")
            ->field("sku.id as id, sku.sku, pic, ori_pic, pic_download_flag,o.client_ordernum")
            ->join('order o', "o.sku=sku.sku", 'left')
            ->group('sku.sku')->count('sku.id');
        print_r($skucount);echo "<br>";
        $time=time();
        $uploadPath0 = "upload/".date("Ym", $time)."/".date("d", $time)."/";
        $uploadPath = env('root_path').'public/'.$uploadPath0;
        if(!file_exists($uploadPath)) {
            mkdir($uploadPath, 0777, true);
        }
        //D:\www_root\mp.020mimo.com\public/upload/202203/22/
        $list = db('sku sku')->where("pic not like 'http://www.020mimo.com%' and pic_download_flag<>2 and ori_pic<>''")
            ->field("sku.id as id, sku.sku, pic, ori_pic, pic_download_flag,o.client_ordernum,o.is_auto_import")
            ->join('order o', "o.sku=sku.sku", 'left')
            ->group('sku.sku')
            //->limit()
            ->order("sku.id desc")->select();
        $domin=$_SERVER['SERVER_NAME'];
        $updateSql="update wx_sku set ";
        $whereSql=" WHERE id IN (".implode(',',array_column($list,'id')).")";
        $picUpdateTxt=$downFlagUpTxt='';
        foreach ($list as $key=>$item) {
            $picUrl=$item['ori_pic'];
            $picNameFull='new'.basename(parse_url($picUrl, PHP_URL_PATH));
            $savePash=$uploadPath.$picNameFull;
            $downRet=$this->downloadPic($picUrl,$savePash);//down pic
            echo $key.":".$item['sku'].":".$item['client_ordernum'].":".$item['is_auto_import'] ;
            echo $downRet['msg']; echo "<br>";
            $visitUrl=$domin."/".$uploadPath0.$picNameFull;
            $skuDataId=$item['id'];
            $downFlagval=$downRet['state']==1?'1':'2';
            $visitUrl=$downRet['state']==1? $visitUrl:'';

            $picUpdateTxt.=" WHEN $skuDataId then '$visitUrl'";
            $downFlagUpTxt.=" WHEN $skuDataId then $downFlagval ";
        }
        $picSql=" pic = CASE id $picUpdateTxt END,";
        $downFlagSql="pic_download_flag = CASE id $downFlagUpTxt END";
        $updateSql.=$picSql.$downFlagSql.$whereSql;
        echo $updateSql;
        echo "<br>执行完成";

    }
    //判断原图失效
    public function downloadPic($url='',$filename){
        //$url='https://lt-plm.oss-cn-shenzhen.aliyuncs.com/Upload/2022-03-10/62299a071485c.jpg?Expires=1648003746&OSSAccessKeyId=LTAI4Fm7N6SgjyxDWE7p7qt4&Signature=rp6nca7EBLEEA1aBtmdcTfo2eic%3D';
        $fileinfo=$errormsg='';
        try {
            $fileinfo=getimagesize($url);echo "<br>";
        } catch (\Exception $e) {
            $errormsg=$e->getMessage();
        }
        $fileAbout=parse_url($url);
        if(isset($fileAbout['query'])){
            $fileAbout=$this->convertUrlQuery($fileAbout['query']);
        }else{
            $fileAbout['Expires']='';
        }
        //记录程序开始的时间
        $BeginTime=microtime(true);
        if(isset($fileinfo[0]) && isset($fileinfo[1])){
            $img=$this->GrabImage($url,$filename);
            //记录程序运行结束的时间
            $EndTime=microtime(true);
            $ret=['msg'=>'download success','state'=>'1','runtime'=>$EndTime-$BeginTime,'img'=>$img];
        }else{
            $EndTime=microtime(true);
            $ret=['msg'=>'下载失败，原图已失效,失效时间'.date('Y-m-d H:i',$fileAbout['Expires']).$errormsg,'state'=>0,'runtime'=>$EndTime-$BeginTime,'img'=>''];
        }
        return $ret;
    }

    //图片下载与保存
    public function GrabImage($url,$filename="") {
        $oldPicPath = basename(parse_url($url, PHP_URL_PATH));
        print_r($oldPicPath);
        //if($ext!=".gif" && $ext!=".jpg"):return false;endif;
        //$filename=date("dMYHis").$ext;
        $filename= $filename==''? $oldPicPath :$filename;
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp2=@fopen($filename, "a");
        fwrite($fp2,$img);
        fclose($fp2);
        return $filename;
    }


    public function getFileSize($url){
        $url = parse_url($url);
        if($fp = @fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)){
            fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])." HTTP/1.1\r\n");
            fputs($fp,"Host:$url[host]\r\n\r\n");
            while(!feof($fp)){
                $tmp = fgets($fp);
                if(trim($tmp) == ''){
                    echo 'file is error';
                    break;
                }else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
                    return trim($arr[1]);
                }
            }
            return null;
        }else{
            return null;
        }
    }

    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
}